<template>
  <div class="transfusionPrescription-create">
    <div class="transfusionPrescription-name">
      <div class="transfusionPrescription-name-left">
        <el-form :model="submitData.prescription" ref="formName" label-width="80px">
          <el-form-item label="处方名称" prop="prescription_name"
                        :rules="{
            required: true,
            message: '请输入处方名称',
            trigger: 'blur'
          }">
            <el-input
              v-model="submitData.prescription.prescription_name"
              style="width: 400px"
              :disabled="detail=='1'"
              placeholder="请输入处方模板名称"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="transfusionPrescription-item-container">
      <div
        class="transfusionPrescription-item"
        v-for="(item, index) in submitData.prescription.patentMedicineList"
        :key="index"
      >
        <div class="item-top-container">
          <div class="item-top-left">
            <p>
              <span class="group-name">组{{ index + 1 }}</span>
            </p>
          </div>
          <div class="item-top-right">
            <el-button type="text" @click="addGroup(index)" :disabled="detail=='1'">添加组</el-button>
            <el-button
              type="text"
              @click="deleteGroup(index)"
              :disabled="submitData.prescription.patentMedicineList.length == 1||detail=='1' ? true : false"
              >删除组</el-button
            >
          </div>
        </div>
        <div class="transfusionPrescription-info-container">
          <table
            class="info-table"
            border="1"
            width="100%"
            cellspacing="0"
            cellpadding="10"
            style="width: 100%; border-collapse: collapse"
          >
            <tbody>
              <tr class="table-td">
                <td class="table-td" align="center">用法</td>
                <td class="table-td">
                  <div class="jishu">
                    <div>
                      <el-autocomplete
                        :disabled="detail=='1'"
                        class="use-info-input"
                        v-model="item.remark.yf"
                        :fetch-suggestions="syyfQuerySearch"
                        placeholder="用法"
                        :trigger-on-focus="true"
                        @change="
                              (val) => {
                                syRemarkChange(val, index);
                              }
                            "
                        @select="
                              (val) => {
                                syyfHandleSelect(val, index);
                              }
                            "
                      >
                        <template slot-scope="{ item }">
                          <div class="useage-item">
                            <div class="name">
                              <span>{{ item }}</span>
                            </div>
                          </div>
                        </template>
                      </el-autocomplete>
                    </div>
                  </div>
                </td>
                <td class="table-td" align="center">滴速</td>
                <td class="table-td mrjl">
                  <div class="jishu">
                    <el-input
                      :disabled="detail=='1'"
                      v-model="item.remark.ds"
                      @change="
                              (val) => {
                                syRemarkChange(val, index);
                              }
                            "
                      placeholder="滴速"
                    ></el-input>
                    <el-autocomplete
                      :disabled="detail=='1'"
                      class="use-info-input"
                      v-model="item.remark.ds_unit"
                      placeholder="单位"
                      :fetch-suggestions="dsQuerySearch"
                      :trigger-on-focus="true"
                      @change="
                              (val) => {
                                syRemarkChange(val, index);
                              }
                            "
                      @select="
                              (val) => {
                                dsHandleSelect(val, index);
                              }
                            "
                    >
                      <template slot-scope="{ item }">
                        <div class="useage-item">
                          <div class="name">
                            <span>{{ item }}</span>
                          </div>
                        </div>
                      </template>
                    </el-autocomplete>
                  </div>
                </td>
                <td class="table-td" align="center">用药频率</td>
                <td class="table-td">
                  <el-autocomplete
                    :disabled="detail=='1'"
                    class="use-info-input"
                    v-model="item.remark.yypl"
                    :fetch-suggestions="syplQuerySearch"
                    placeholder="用药频率"
                    :trigger-on-focus="true"
                    @change="
                            (val) => {
                              syRemarkChange(val, index);
                            }
                          "
                    @select="
                            (val) => {
                              syplHandleSelect(val, index);
                            }
                          "
                  >
                    <template slot-scope="{ item }">
                      <div class="useage-item">
                        <div class="name">
                          <span>{{ item }}</span>
                        </div>
                      </div>
                    </template>
                  </el-autocomplete>
                </td>
              </tr>
              <tr class="table-td">
                <td class="table-td" align="center">起始日期</td>
                <td class="table-td" colspan="3">
                  <div>
                    <!-- v-model="item.remark.qsrq" -->
                    <el-date-picker
                      disabled
                      value="开处方时自动带入"
                      type="date"
                      :picker-options="pickerOptions"
                      value-format="yyyy-MM-ddTHH:mm:ss.000Z"
                      placeholder="开处方时自动带入"
                    >
                    </el-date-picker>
                  </div>
                </td>
                <td class="table-td" align="center">连续天数</td>
                <td class="table-td">
                  <div class="jishu">
                    <el-input
                      :disabled="detail=='1'"
                      v-model="item.remark.lxts"
                      @change="
                              (val) => {
                                syRemarkChange(val, index);
                              }
                            "
                      placeholder="天数"
                    ></el-input>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <el-form
          :model="item"
          ref="patentMedicineValidateForm"
          label-width="100px"
          class="transfusionPrescription-form"
          :disabled="detail=='1'"
        >
          <el-form-item class="form-item-header">
            <div class="top-header">
              <div class="top-left">
                <p>药品</p>
              </div>
            </div>
          </el-form-item>
          <el-table
            :data="item.details"
            border
            style="width: 100%"
            :show-header="false"
            :cell-style="{ borderColor: '#DFE2E8' }"
          >
            <el-table-column label="药品名称" align="center" width="100px">
              <template slot-scope="scope">
                <div class="item-title">
                  <p>药品{{ scope.$index + 1 }}</p>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="药品名称" width="350px">
              <template slot-scope="scope">
                <el-autocomplete
                  class="use-info-input"
                  style="width: 350px"
                  v-model="scope.row.product_name"
                  :fetch-suggestions="syProQuerySearch"
                  :trigger-on-focus="false"
                  @change="
                        (val) => {
                          syDetailChange(val, index,scope.$index,'product');
                        }
                      "
                  @select="
                        (item) => {
                          syProHandleSelect(item, index,scope.$index);
                        }
                      "
                >
                  <template slot="suffix" v-if="scope.row.own ? false : true">
                    <el-tooltip
                      v-if="scope.row.product_name!==''"
                      content="该药品不在您的药库中或者库存不足，建议您更换其他药品"
                      placement="bottom"
                      effect="light"
                    >
                      <i class="el-icon-warning"> </i>
                    </el-tooltip>
                  </template>
                  <template slot-scope="{ item }">
                    <div
                      class="product-item-container"
                      style="
                            display: flex;
                            justify-content: flex-start;
                            align-items: flex-start;
                          "
                    >
                      <div class="icon-container" style="margin-right: 5px">
                        <i
                          class="el-icon-success"
                          style="color: green"
                          v-if="item.Own"
                        ></i>
                        <i class="el-icon-warning" v-else></i>
                      </div>
                      <div class="product-item" style="padding: 5px 0px">
                        <div
                          class="name"
                          style="font-weight: bold; line-height: 22px"
                        >
                              <span class="name-name">{{
                                item.product_name
                              }}</span
                              ><span class="name-pack">({{ item.pack }})</span>
                        </div>
                        <div
                          class="producer"
                          style="color: #999; line-height: 22px"
                        >
                          <span>{{ item.production }}</span>
                        </div>
                      </div>
                    </div>
                  </template>
                </el-autocomplete>
              </template>
            </el-table-column>
            <el-table-column  width="100px" align="center">
              <template slot-scope="scope">
                <el-input
                  class="num-input"
                  v-model="scope.row.single_dose"
                  @change="
                        (val) => {
                          syDetailChange(val, index,scope.$index);
                        }
                      "
                  placeholder="剂量"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column>
              <template slot-scope="scope">
                <div>
                  <el-autocomplete
                    class="inline-input"
                    v-model="scope.row.single_unit"
                    :fetch-suggestions="singleUnitQuerySearch"
                    placeholder="单位"
                    :trigger-on-focus="true"
                    @change="
                        (val) => {
                          syDetailChange(val, index,scope.$index);
                        }
                      "
                    @select="
                        (val) => {
                          sySingleUnitHandleSelect(val, index,scope.$index);
                        }
                      "
                  >
                    <template slot-scope="{ item }">
                      <div class="useage-item">
                        <div class="name">
                          <span>{{ item }}</span>
                        </div>
                      </div>
                    </template>
                  </el-autocomplete>
                </div>
              </template>
            </el-table-column>
            <el-table-column>
              <template slot-scope="scope">
                <el-input
                  class="num-input"
                  v-model="scope.row.skin_test"
                  @change="
                        (val) => {
                          syDetailChange(val, index,scope.$index);
                        }
                      "
                  placeholder="皮试"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column>
              <template slot-scope="scope">
                <el-input
                  class="num-input"
                  v-model="scope.row.number"
                  placeholder="开药量"
                  @change="
                        (val) => {
                          syDetailChange(val, index,scope.$index );
                        }
                      "
                  @keyup.native="
                        (val) => {
                          syNumberChange(val, index,scope.$index);
                        }
                      "
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column >
              <template slot-scope="scope">
                <div>
                  <el-autocomplete
                    class="inline-input"
                    v-model="scope.row.unit"
                    :fetch-suggestions="numberUnitQuerySearch"
                    placeholder="单位"
                    :trigger-on-focus="true"
                    @change="
                        (val) => {
                          syDetailChange(val, index, scope.$index);
                        }
                      "
                    @select="
                        (val) => {
                          syNumberUnitHandleSelect(val, index,scope.$index);
                        }
                      "
                  >
                    <template slot-scope="{ item }">
                      <div class="useage-item">
                        <div class="name">
                          <span>{{ item }}</span>
                        </div>
                      </div>
                    </template>
                  </el-autocomplete>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="30px" v-if="detail!='1'">
              <template slot-scope="scope">
                <div>
                  <el-button
                    class="icon-btn"
                    icon="el-icon-delete"
                    @click.prevent="removePatentItem(scope.$index, index)"
                  ></el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-form-item class="form-item-btn">
            <div class="btn-container">
              <el-button type="text" @click.prevent="addPatentItem(-1, index)"
                >+新增药品</el-button
              >
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import { productSearch, productDetail } from "@/api/product.js";
import publicRemind from "@/assets/js/publicRemind.js";
export default {
  props: {
    editData: {
      type: Object,
      default: null,
    },
    detail:{
      type: String,
    }
  },
  data() {
    return {
      remindData: publicRemind.remind,
      submitData: {
        prescription: {
          prescription_name: "",
          category_key: "sycf",
          category_name: "输液处方",
          patentMedicineList: [
            {
              remark: {
                yf: "",
                mrjl: "",
                ds: "",
                qsrq: new Date(),
                lxts: "",
              },
              details: [
                {
                  product_id: 0,
                  product_name: "",
                  pack: "", // 规格
                  single_dose: "",
                  single_unit: "",
                  number: "", // 数量
                  price: 0, // 价格
                  amount: 0, // 总价
                  unit: "",
                  group: 1,
                },
                {
                  product_id: 0,
                  product_name: "",
                  pack: "", // 规格
                  single_dose: "",
                  single_unit: "",
                  number: "", // 数量
                  price: 0, // 价格
                  amount: 0, // 总价
                  unit: "",
                  group: 1,
                },
              ],
            },
          ],
          group_count: 1,
        },
      },
      pickerOptions: {
        disabledDate(time) {
          //此条为设置禁止用户选择今天之前的日期，包含今天。
          return time.getTime() <= Date.now() - 8.64e7;
        }
      },
    };
  },
  watch: {
    editData: {
      handler(newval, oldval) {
        if (newval) {
          this.submitData = JSON.parse(JSON.stringify(this.editData));
          console.log(this.editData,this.submitData);
        }
      },
      immediate: true,
    },
  },
  mounted() {
    this.restaurants = this.loadAll();
  },
  methods: {
    submitForm() {
      var boo;
      this.$refs.formName.validate((valid) => {
        if (valid) {
          boo = true
        } else {
          boo = false;
        }
      });
      return boo
    },
    nameChange(val){
      console.log(val)
    },
    //将数据传给父组件
    emitData() {
      let copyData = JSON.parse(JSON.stringify(this.submitData));
      let remark = {};
      let details = [];
      this.submitData.prescription.patentMedicineList.group_count = this.submitData.prescription.patentMedicineList.length;
      this.submitData.prescription.patentMedicineList.forEach((item, index) => {
        item.details.forEach((itm, idx) => {
          itm.group = index + 1;
          if(itm.product_name){
            details.push(itm)
          }
        });
        Object.assign(remark, { [index+1]: item.remark });
      });
      Object.assign(copyData.prescription, { remark: remark, details: details });
      this.$delete(copyData.prescription, "patentMedicineList");
      return copyData;
    },
    // 输液产品联想
    async syProQuerySearch(queryString, cb) {
      let pro = await productSearch({ prefix: queryString, size: 10 });
      this.syProductList = pro.data.ElasticProduct || [];
      var results = this.syProductList;
      cb(results);
    },
    syDetailChange(val, index, idx, type) {
      if (type == "product") {
        this.submitData.prescription.patentMedicineList[index].details[idx].own = false
      }else if(this.submitData.prescription.patentMedicineList[index].details[idx].stock<=0){
        this.submitData.prescription.patentMedicineList[index].details[idx].own = false
        this.submitData.prescription.patentMedicineList[index].details[idx].price = 0
      }
      if (this.submitData.prescription.patentMedicineList[index].update_status !== 2) {
        this.submitData.prescription.patentMedicineList[index].update_status = 1;
      }
    },
    async syProHandleSelect(item, index, idx) {
      let product = await productDetail({ default_id: item.id });
      this.submitData.prescription.patentMedicineList[index].details[idx].own = product.data ? true : item.Own;
      this.submitData.prescription.patentMedicineList[index].details[
        idx
        ].product_id = product.data ? product.data.id : item.id;
      this.submitData.prescription.patentMedicineList[index].details[
        idx
        ].product_name = product.data
        ? product.data.product_name
        : item.product_name;
      this.submitData.prescription.patentMedicineList[index].details[idx].pack = product.data
        ? product.data.pack
        : item.pack;
      this.submitData.prescription.patentMedicineList[index].details[idx].number = 1;
      this.submitData.prescription.patentMedicineList[index].details[idx].price = product.data
        ? product.data.price
        : Number(item.price || 0);
      let price = this.submitData.prescription.patentMedicineList[index].details[idx].number;
      let num = this.submitData.prescription.patentMedicineList[index].details[idx].price;
      this.submitData.prescription.patentMedicineList[index].details[idx].amount = price * num;
      this.submitData.prescription.patentMedicineList[index].details[idx].unit = product.data
        ? product.data.number_unit
        : item.number_unit;
    },
    syDetailChange(val, index,idx) {
      // if (this.submitData.prescription.patentMedicineList[index].details[idx].update_status !== 2) {
      //   this.submitData.prescription.patentMedicineList[index].details[idx].update_status = 1;
      // }
    },
    // 输液用法输入联想--开始
    syyfQuerySearch(queryString, cb) {
      var restaurants = this.remindData.shuye_usage;
      var results = queryString
        ? restaurants.filter(this.commonCreateFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    commonCreateFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    syyfHandleSelect(val, index) {
      this.submitData.prescription.patentMedicineList[index].remark.yf = val;
    },
    // 滴速输入联想
    dsQuerySearch(queryString, cb) {
      var restaurants = this.remindData.ds_unit;
      var results = queryString
        ? restaurants.filter(this.commonCreateFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    dsHandleSelect(val, index) {
      this.submitData.prescription.patentMedicineList[index].remark.ds_unit = val;
    },
    // 输液用药频率输入联想--开始
    syplQuerySearch(queryString, cb) {
      var restaurants = this.remindData.eat_rate;
      var results = queryString
        ? restaurants.filter(this.commonCreateFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    syplHandleSelect(val, index) {
      this.submitData.prescription.patentMedicineList[index].remark.yypl = val;
    },
    // 剂量单位输入联想--开始
    singleUnitQuerySearch(queryString, cb) {
      var restaurants = this.remindData.dose_unit;
      var results = queryString
        ? restaurants.filter(this.commonCreateFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    sySingleUnitHandleSelect(val, index, idx) {
      this.submitData.prescription.patentMedicineList[index].details[idx].single_unit = val;
    },
    // 销售单位输入联想--开始
    numberUnitQuerySearch(queryString, cb) {
      var restaurants = this.remindData.number_unit;
      var results = queryString
        ? restaurants.filter(this.commonCreateFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    syNumberUnitHandleSelect(val, index, idx) {
      this.submitData.prescription.patentMedicineList[index].details[idx].unit = val;
    },
    syRemarkChange(val, index) {
      // if (this.submitData.prescription.patentMedicineList[index].update_status !== 2) {
      //   this.submitData.prescription.patentMedicineList[index].update_status = 1;
      // }
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    // 添加组
    addGroup(index) {
      let addItem = {
          remark: {
            fy: "",
            mrjl: "",
            ds: "",
            qsrq: "",
            lxts: "",
            ds_unit:'',
          },
          details: [
            {
              own:true,
              product_id: 0,
              product_name: "",
              pack: "", // 规格
              single_dose: "",
              single_unit: "",
              number: "", // 数量
              price: 0, // 价格
              amount: 0, // 总价
              unit: "",
              group: 1,
            },
            {
              own:true,
              product_id: 0,
              product_name: "",
              pack: "", // 规格
              single_dose: "",
              single_unit: "",
              number: "", // 数量
              price: 0, // 价格
              amount: 0, // 总价
              unit: "",
              group: 1,
            },
          ],
        }
      this.submitData.prescription.patentMedicineList.push(addItem);
      this.submitData.prescription.patentMedicineList.group_count += 1;
      this.$forceUpdate()
    },
    // 删除组
    deleteGroup(index) {
      this.submitData.prescription.patentMedicineList.splice(index, 1);
      this.submitData.prescription.patentMedicineList.group_count -= 1;
      this.$forceUpdate()
    },
    removePatentItem(idx, index) {
      // var idx = this.patentMedicineList[index].domains.indexOf(item);
      // if (idx !== -1) {
      //   this.patentMedicineList[index].domains.splice(idx, 1);
      // }
      this.submitData.prescription.patentMedicineList[index].details.splice(
        idx,
        1
      );
    },
    addPatentItem(idx, index) {
      console.log(idx, index);
      if (
        idx == -1 ||
        idx ==
          this.submitData.prescription.patentMedicineList[index].details
            .length -
            1
      ) {
        console.log(this.submitData.prescription.patentMedicineList[index].details)
        if(this.submitData.prescription.patentMedicineList[index].details.length==0){
          let groups = 1
          this.submitData.prescription.patentMedicineList[index].details.push({
            own:true,
            product_id: 0,
            product_name: "",
            pack: "", // 规格
            single_dose: "",
            single_unit: "",
            number: "", // 数量
            price: 0, // 价格
            amount: 0, // 总价
            unit: "",
            group: groups,
            key: Date.now(),
          });
        }else{
          let groups = this.submitData.prescription.patentMedicineList[index]
            .details[0].group;
          this.submitData.prescription.patentMedicineList[index].details.push({
            own:true,
            product_id: 0,
            product_name: "",
            pack: "", // 规格
            single_dose: "",
            single_unit: "",
            number: "", // 数量
            price: 0, // 价格
            amount: 0, // 总价
            unit: "",
            group: groups,
            key: Date.now(),
          });
        }
        // let groups = this.submitData.prescription.patentMedicineList[index]
        //   .details[0].group;
        // this.submitData.prescription.patentMedicineList[index].details.push({
        //   own:true,
        //   product_id: 0,
        //   product_name: "",
        //   pack: "", // 规格
        //   single_dose: "",
        //   single_unit: "",
        //   number: "", // 数量
        //   price: 0, // 价格
        //   amount: 0, // 总价
        //   unit: "",
        //   group: groups,
        //   key: Date.now(),
        // });
      }
    },
    handleSelect(item) {
      console.log(item);
    },
    loadAll() {
      return [
        { value: "三全鲜食（北新泾店）", address: "长宁区新渔路144号" },
        {
          value: "Hot honey 首尔炸鸡（仙霞路）",
          address: "上海市长宁区淞虹路661号",
        },
        {
          value: "新旺角茶餐厅",
          address: "上海市普陀区真北路988号创邑金沙谷6号楼113",
        },
        { value: "泷千家(天山西路店)", address: "天山西路438号" },
        {
          value: "胖仙女纸杯蛋糕（上海凌空店）",
          address: "上海市长宁区金钟路968号1幢18号楼一层商铺18-101",
        },
        { value: "贡茶", address: "上海市长宁区金钟路633号" },
        {
          value: "豪大大香鸡排超级奶爸",
          address: "上海市嘉定区曹安公路曹安路1685号",
        },
        {
          value: "茶芝兰（奶茶，手抓饼）",
          address: "上海市普陀区同普路1435号",
        },
        { value: "十二泷町", address: "上海市北翟路1444弄81号B幢-107" },
        { value: "星移浓缩咖啡", address: "上海市嘉定区新郁路817号" },
        { value: "阿姨奶茶/豪大大", address: "嘉定区曹安路1611号" },
        { value: "新麦甜四季甜品炸鸡", address: "嘉定区曹安公路2383弄55号" },
      ];
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/scss/templates/modules/transfusionPrescription.scss";
</style>
<style>
  .transfusionPrescription-create .el-input__suffix {
    position: absolute;
    height: 100%;
    right: 5px;
    top: 8px;
    text-align: center;
    color: #D23137;
    transition: all 0.3s;
    pointer-events: none;
  }
</style>
